// 线索导出功能
(function() {
    'use strict';
    
    let selectedClues = [];
    
    // 初始化导出功能
    function initExportFunction() {
        console.log('初始化导出功能...');
        
        // 更新选中的线索
        function updateSelectedClues() {
            const checkboxes = document.querySelectorAll('.clue-checkbox:checked');
            selectedClues = Array.from(checkboxes).map(cb => cb.value);
            
            console.log('当前选中线索:', selectedClues);
            
            // 更新导出按钮状态
            const exportBtn = document.getElementById('exportBtn');
            const selectedCountBadge = document.getElementById('selectedCountBadge');
            
            if (exportBtn && selectedCountBadge) {
                selectedCountBadge.textContent = selectedClues.length;
                
                if (selectedClues.length > 0) {
                    exportBtn.classList.remove('disabled');
                    exportBtn.style.opacity = '1';
                    selectedCountBadge.className = 'badge bg-primary ms-1';
                } else {
                    exportBtn.classList.add('disabled');
                    exportBtn.style.opacity = '0.6';
                    selectedCountBadge.className = 'badge bg-secondary ms-1';
                }
            }
            
            // 更新清空选择按钮和批量操作区域
            const clearSelectionBtn = document.getElementById('clearSelectionBtn');
            const clearSelectionBadge = document.getElementById('clearSelectionBadge');
            const batchActionsGroup = document.getElementById('batchActionsGroup');
            
            const hasSelection = selectedClues.length > 0;
            
            // 更新清空选择按钮的显示
            if (clearSelectionBtn && clearSelectionBadge) {
                if (hasSelection) {
                    clearSelectionBadge.textContent = selectedClues.length;
                    clearSelectionBtn.style.display = 'inline-block';
                } else {
                    clearSelectionBtn.style.display = 'none';
                }
            }
            
            // 更新批量操作区域的样式
            if (batchActionsGroup) {
                if (hasSelection) {
                    batchActionsGroup.classList.add('has-selection');
                } else {
                    batchActionsGroup.classList.remove('has-selection');
                }
            }
        }
        
        // 绑定复选框事件
        function bindCheckboxEvents() {
            // 移除之前可能存在的事件监听器
            document.removeEventListener('change', handleCheckboxChange);
            
            // 全选复选框
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                // 移除现有的任何事件监听器
                selectAllCheckbox.removeEventListener('change', handleSelectAllChange);
                selectAllCheckbox.addEventListener('change', handleSelectAllChange);
                console.log('全选复选框事件已绑定');
            }
            
            // 使用更具体的事件委托，只监听表格内的复选框
            document.addEventListener('change', handleCheckboxChange);
            console.log('复选框事件委托已绑定');
        }
        
        // 处理复选框变化事件
        function handleCheckboxChange(e) {
            // 只处理线索复选框，忽略其他复选框
            if (e.target.classList.contains('clue-checkbox')) {
                console.log('复选框变化:', e.target.value, e.target.checked);
                updateSelectedClues();
                
                // 更新全选状态
                const allCheckboxes = document.querySelectorAll('.clue-checkbox');
                const checkedCheckboxes = document.querySelectorAll('.clue-checkbox:checked');
                const selectAll = document.getElementById('selectAll');
                
                if (selectAll) {
                    selectAll.checked = checkedCheckboxes.length === allCheckboxes.length;
                    selectAll.indeterminate = checkedCheckboxes.length > 0 && checkedCheckboxes.length < allCheckboxes.length;
                }
            }
        }
        
        // 处理全选复选框变化
        function handleSelectAllChange() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.clue-checkbox');
            
            console.log('全选复选框变化:', selectAll.checked, '复选框数量:', checkboxes.length);
            
            if (selectAll && checkboxes.length > 0) {
                checkboxes.forEach(checkbox => {
                    checkbox.checked = selectAll.checked;
                });
                updateSelectedClues();
            }
        }
        
        // 防抖变量
        let exportTimeout = null;
        let isExporting = false;
        
        // 导出函数
        function exportSelectedClues() {
            console.log('=== 外部导出函数被调用 ===');
            console.log('当前选中的线索:', selectedClues);
            console.log('导出状态:', { isExporting, exportTimeout });
            
            // 防止重复点击
            if (isExporting) {
                console.log('导出正在进行中，忽略重复点击');
                return;
            }
            
            // 清除之前的超时
            if (exportTimeout) {
                clearTimeout(exportTimeout);
                exportTimeout = null;
            }
            
            if (selectedClues.length === 0) {
                alert('请先选择要导出的线索');
                return;
            }
            
            const token = localStorage.getItem('adminToken');
            if (!token) {
                alert('请先登录');
                window.location.href = '/admin/login.html';
                return;
            }
            
            // 设置导出状态
            isExporting = true;
            
            // 获取按钮并设置加载状态
            const exportBtn = document.getElementById('exportBtn');
            let originalText = '';
            
            if (exportBtn) {
                originalText = exportBtn.innerHTML;
                exportBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>导出中...';
                exportBtn.disabled = true;
            }
            
            try {
                // 构建导出URL
                const params = new URLSearchParams({
                    format: 'excel',
                    clue_ids: selectedClues.join(','),
                    token: token
                });
                
                const exportUrl = `/api/admin/clues/export?${params.toString()}`;
                console.log('导出URL:', exportUrl);
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = exportUrl;
                link.download = `线索导出_${new Date().toISOString().split('T')[0]}.xls`;
                link.style.display = 'none';
                
                // 添加到页面并触发点击
                document.body.appendChild(link);
                link.click();
                
                // 立即移除链接
                setTimeout(() => {
                    if (link.parentNode) {
                        document.body.removeChild(link);
                        console.log('下载链接已移除');
                    }
                }, 100);
                
                console.log('导出请求已发送');
                
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败：' + error.message);
            } finally {
                // 恢复按钮状态和导出状态
                exportTimeout = setTimeout(() => {
                    if (exportBtn) {
                        exportBtn.innerHTML = originalText;
                        exportBtn.disabled = false;
                    }
                    isExporting = false;
                    exportTimeout = null;
                    console.log('导出状态已重置');
                }, 2000);
            }
        }
        
        // 绑定导出按钮事件
        function bindExportButton() {
            const exportBtn = document.getElementById('exportBtn');
            if (exportBtn) {
                // 移除现有的onclick属性
                exportBtn.removeAttribute('onclick');
                
                // 添加新的事件监听器
                exportBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    exportSelectedClues();
                });
                
                console.log('导出按钮事件已绑定');
            }
        }
        
        // 测试函数
        window.testExport = function() {
            console.log('测试导出功能');
            // 自动选择前两个线索
            const checkboxes = document.querySelectorAll('.clue-checkbox');
            if (checkboxes.length >= 2) {
                checkboxes[0].checked = true;
                checkboxes[1].checked = true;
                updateSelectedClues();
                setTimeout(() => {
                    exportSelectedClues();
                }, 500);
            } else {
                console.log('没有可选择的线索');
            }
        };
        
        window.getSelectedClues = function() {
            return selectedClues;
        };
        
        // 暴露清空选择函数
        window.clearSelection = function() {
            selectedClues = [];
            
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            }
            
            // 清空所有复选框
            document.querySelectorAll('.clue-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            
            updateSelectedClues();
        };
        
        // 暴露重置函数，供主页面表格重新加载时调用
        window.resetExportState = function() {
            console.log('重置导出状态...');
            selectedClues = [];
            
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            }
            
            updateSelectedClues();
        };
        
        // 暴露手动更新选中状态的函数
        window.updateSelectedClues = function() {
            updateSelectedClues();
        };
        
        // 暴露强制重新绑定事件的函数
        window.rebindExportEvents = function() {
            console.log('重新绑定导出事件...');
            bindCheckboxEvents();
            bindExportButton();
            updateSelectedClues();
        };
        
        // 初始化
        bindCheckboxEvents();
        bindExportButton();
        updateSelectedClues();
        
        console.log('导出功能初始化完成');
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟初始化以确保主页面脚本先执行
            setTimeout(initExportFunction, 100);
        });
    } else {
        // 如果页面已经加载完成，延迟初始化
        setTimeout(initExportFunction, 100);
    }
    
    // 添加全局调试函数
    window.debugExportJS = function() {
        console.log('=== 导出JS调试信息 ===');
        console.log('selectedClues:', selectedClues);
        console.log('isExporting:', isExporting);
        console.log('导出按钮:', document.getElementById('exportBtn'));
        console.log('全选复选框:', document.getElementById('selectAll'));
        console.log('线索复选框数量:', document.querySelectorAll('.clue-checkbox').length);
        console.log('选中的复选框数量:', document.querySelectorAll('.clue-checkbox:checked').length);
        
        // 检查选中的复选框值
        const checkedValues = Array.from(document.querySelectorAll('.clue-checkbox:checked')).map(cb => cb.value);
        console.log('DOM中选中的复选框值:', checkedValues);
        console.log('selectedClues数组:', selectedClues);
        console.log('数据是否同步:', JSON.stringify(checkedValues) === JSON.stringify(selectedClues));
        
        return {
            selectedClues,
            isExporting,
            exportBtn: !!document.getElementById('exportBtn'),
            selectAll: !!document.getElementById('selectAll'),
            totalCheckboxes: document.querySelectorAll('.clue-checkbox').length,
            checkedCheckboxes: document.querySelectorAll('.clue-checkbox:checked').length,
            checkedValues,
            dataSync: JSON.stringify(checkedValues) === JSON.stringify(selectedClues)
        };
    };
    
    // 强制修复选中状态
    window.forceFixSelection = function() {
        console.log('=== 强制修复选中状态 ===');
        
        // 重新初始化
        isExporting = false;
        if (exportTimeout) {
            clearTimeout(exportTimeout);
            exportTimeout = null;
        }
        
        // 重新绑定事件
        initExportFunction();
        
        // 强制更新选中状态
        updateSelectedClues();
        
        console.log('修复完成，当前状态:', debugExportJS());
        return '修复完成，请重新尝试选择和导出';
    };
    
})(); 